package com.apache.rpc.controller;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.database.model.TaskEntity;
import com.apache.rpc.common.RpcUtil;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.rpc.entity.RpcDatasource;
import com.apache.rpc.entity.RpcMonitoring;
import com.apache.rpc.entity.SystemConfig;
import com.apache.rpc.manager.*;
import com.apache.rpc.service.impl.helper.CacheTactics;
import com.apache.task.api.ScheduledExecutor;
import com.apache.task.util.XmlReader;
import com.apache.tools.MD5Utils;
import com.apache.tools.OsUtils;
import com.apache.tools.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 *
 * @author dyh 创建时间：2018年02月12日
 */
@Controller
public class RpcWelcomeAction {

    @Autowired
    protected InterfaceRegisterManager interfaceRegisterManager;

    @Autowired
    protected RpcMonitoringManager rpcMonitoringManager;

    @Autowired
    protected SystemConfigManager systemConfigManager;

    @Autowired
    protected RpcDatasourceManager rpcDatasourceManager;

    @Autowired
    protected CacheTactics interfaceRegisterCacheTactics;

    @Autowired
    protected DynamicDatabaseManager taskTimerManager;

    /**
     * 跳到rpc-index页
     */
    @RequestMapping(value = "/rpc/index", method = RequestMethod.GET)
    public String toIndex(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        data.put("title", "RPC系统管理控制台");
        data.put("userName", "admin");
        return "/protocol/rpc-index";
    }

    /**
     * 定时任务设置开关
     */
    @RequestMapping(value = "/openTask", method = RequestMethod.GET)
    @ResponseBody
    public ResultMsg openTask(HttpServletRequest request, String isOpen) {
        ResultMsg msg = new ResultMsg("T", "操作成功");
        isOpen = StrUtil.doNull(isOpen, "true");
        CacheTactics.setIsOpenTask(Boolean.parseBoolean(isOpen));
        return msg;
    }

    /**
     * 查看缓存
     */
    @RequestMapping(value = "/viewCache", method = RequestMethod.GET)
    @ResponseBody
    public Object viewCache(HttpServletRequest request, String type) {
        Object obj = null;
        String key = request.getParameter("id");
        if ("register".equalsIgnoreCase(type)) {//key=beanId
            String registerId = request.getParameter("registerId");
            List<InterfaceRegister> list = (List) LoadCacheFactory.getInstance().getCacheManager("")
                    .getCacheObjectByKey("interfaceRegister_" + key);
            if (null != list) {
                for (InterfaceRegister reg : list) {
                    if (registerId.equals(reg.getRegisterId())) {
                        obj = reg;
                        break;
                    }
                }
            }
        } else if ("config".equalsIgnoreCase(type)) {//key=config.getFileName()
            obj = LoadCacheFactory.getInstance().getCacheManager("").getCacheObjectByKey(key);
        } else if ("datasource".equalsIgnoreCase(type)) {//key=config.getSysEname()
            String cacheKey = "rpc_datasource_" + key;
            obj = LoadCacheFactory.getInstance().getCacheManager("").getCacheObjectByKey(cacheKey);
        } else {
            obj = LoadCacheFactory.getInstance().getCacheManager("").getCacheObjectByKey(key);
        }
        if (null == obj) {
            return "无";
        }
        return obj;
    }

    /**
     * 跳到登录页
     */
    @RequestMapping(value = "/cacheKeys", method = RequestMethod.GET)
    public String cacheKeys(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        List<String> list = LoadCacheFactory.getInstance().getCacheManager("").getAllKeys();
        Collections.sort(list);
        data.put("cacheKeys", list);
        return "/cache-list";
    }

    @RequestMapping("/delCache")
    @ResponseBody
    public ResultMsg delCache(HttpServletRequest request) {
        String key = request.getParameter("id");
        if (StrUtil.isNull(key)) {
            return new ResultMsg("F", "缺少必要参数！");
        }
        LoadCacheFactory.getInstance().getCacheManager("").removeCacheObject(key);
        return new ResultMsg("T", "删除成功！");
    }

    /**
     * 跳到列表页
     */
    @RequestMapping(value = "/protocol/list", method = RequestMethod.GET)
    public String toProtocolList(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        return "/protocol/interface-list";
    }

    /**
     * 跳到新增页
     */
    @RequestMapping(value = "/protocol/save", method = RequestMethod.GET)
    public String toSave(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        String id = request.getParameter("id");
        if (StrUtil.isNull(id)) {//新增
            data.put("item", new InterfaceRegister());
        } else {
            ParamsVo<InterfaceRegister> vo = new ParamsVo();
            vo.setInfoId(id);
            data.put("item", interfaceRegisterManager.getInfoById(vo));
        }
        return "/protocol/interface-save";
    }

    /**
     * 跳到列表页
     */
    @RequestMapping(value = "/config/list", method = RequestMethod.GET)
    public String toConifgList(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        return "/sysconfig/config-list";
    }

    /**
     * 跳到新增页
     */
    @RequestMapping(value = "/config/save", method = RequestMethod.GET)
    public String toConfigSave(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        String id = request.getParameter("id");
        if (StrUtil.isNull(id)) {//新增
            data.put("item", new SystemConfig());
            data.put("isAdd", "true");
        } else {
            ParamsVo<SystemConfig> vo = new ParamsVo();
            vo.setInfoId(id);
            data.put("isAdd", "false");
            data.put("item", systemConfigManager.getInfoById(vo));
        }
        return "/sysconfig/config-save";
    }

    @RequestMapping("/config/list!data.action")
    @ResponseBody
    public Object dataConfig(HttpServletRequest request, String page, String rows) {

        ParamsVo<SystemConfig> vo = new ParamsVo<SystemConfig>();
        SystemConfig register = new SystemConfig();
        if (Validator.isNotNull(request.getParameter("fileName"))) {
            register.setFileName(request.getParameter("fileName"));
        }
        vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
        vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
        vo.setObj(register);
        Page pageList = systemConfigManager.getPageInfo(vo);
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", pageList.getCount());
        mapData.put("rows", pageList.getPageObjects());
        return mapData;
    }

    @RequestMapping("/config/loadCache")
    @ResponseBody
    public ResultMsg loadCache(HttpServletRequest request) {
        ParamsVo vo = new ParamsVo();
        SystemConfig config = new SystemConfig();
        vo.setObj(config);
        vo.setMethodKey("initCache");
        systemConfigManager.execute(vo);
        return new ResultMsg("T", "重新加载成功！");
    }

    @RequestMapping(value = "/config/save.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveConfig(HttpServletRequest request, HttpServletResponse response,
            SystemConfig item) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        String isAdd = request.getParameter("isAdd");
        if (Validator.isNull(item.getFileName())) {
            rmsg = new ResultMsg("F", "文件名称不能为空！");
            return rmsg;
        }
        ParamsVo<SystemConfig> vo = new ParamsVo<SystemConfig>();
        vo.setObj(item);
        String id = "";
        boolean mark = false;
        if ("false".equals(isAdd) && item != null) {
            mark = systemConfigManager.editInfo(vo);
        } else {
            id = systemConfigManager.saveInfo(vo);
        }
        if (("false".equals(isAdd) && !mark) || ("true".equals(isAdd) && StrUtil.isNull(id))) {
            rmsg.setFlag("F");
            rmsg.setMsg("操作失败！");
        }
        return rmsg;
    }

    @RequestMapping(value = "/config/del.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteConfig(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<SystemConfig> vo = new ParamsVo();
        if (StrUtil.isNotNull(id)) {
            vo.setInfoId(id);
            boolean mark = systemConfigManager.deleteInfo(vo);
            if (!mark) {
                rmsg.setFlag("F");
                rmsg.setMsg("删除失败！");
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请不要恶意操作！");
        }

        return rmsg;
    }

    /**
     * 跳到列表页
     */
    @RequestMapping(value = "/task/list", method = RequestMethod.GET)
    public String toTaskList(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        return "/timetask/task-list";
    }

    /**
     * 跳到新增页
     */
    @RequestMapping(value = "/task/save", method = RequestMethod.GET)
    public String toTaskSave(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        TaskEntity task = new TaskEntity();
        String key = request.getParameter("key");
        if (StrUtil.isNotNull(key)) {
            //taskTimerManager
            String isFile = StrUtil.doNull(RpcUtil.getInstance().getValueByKey("read.file.database"),"file");
            if("file".equalsIgnoreCase(isFile)){
                List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
                for (TaskEntity te : list) {
                    if (key.equals(te.getTaskKey())) {
                        task = te;
                        break;
                    }
                }
            }else{
                ParamsVo vo = new ParamsVo();
                vo.setInfoId(key);
                task = (TaskEntity)taskTimerManager.getInfoById(vo);
            }
        }
        data.put("item", task);
        return "/timetask/task-save";
    }

    /**
     * 跳到列表页
     */
    @RequestMapping(value = "/rpc/monitoring", method = RequestMethod.GET)
    public String monitoringList(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        return "/protocol/monitoring-list";
    }

    @RequestMapping("/rpc/list!data.action")
    @ResponseBody
    public Object dataMonitoring(HttpServletRequest request, String page, String rows) {
        ParamsVo<RpcMonitoring> vo = new ParamsVo<RpcMonitoring>();
        RpcMonitoring register = new RpcMonitoring();
        if (Validator.isNotNull(request.getParameter("beanId"))) {
            register.setBeanId(request.getParameter("beanId"));
        }
        if (Validator.isNotNull(request.getParameter("methodKey"))) {
            register.setMethodKey(request.getParameter("methodKey"));
        }
        if (Validator.isNotNull(request.getParameter("serverAddr"))) {
            register.setServerAddr(request.getParameter("serverAddr"));
        }
        vo.setParams("pageSize", Validator.getDefaultStr(rows, "20"));
        vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
        vo.setObj(register);
        Page pageList = rpcMonitoringManager.getPageInfo(vo);
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", pageList.getCount());
        mapData.put("rows", pageList.getPageObjects());
        return mapData;
    }

    /**
     * description:  添加线程
     */
    @RequestMapping(value = "/task/saveTask.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveTask(HttpServletRequest request, HttpServletResponse response,
            TaskEntity item) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        String isAdd = "false";
        if (StrUtil.isNull(item.getTaskKey())) {
            isAdd = "true";
        }
        String id = "";
        boolean mark = false;
        if (item.getIntervalType() == 1) {//如果选择按每天定时执行,小时项未填写则默认此项为1
            if (item.getHour() <= 1) {
                item.setHour(1l);
            }
        }
        //taskTimerManager
        String isFile = StrUtil.doNull(RpcUtil.getInstance().getValueByKey("read.file.database"),"file");
        if("file".equalsIgnoreCase(isFile)){
            List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
            if ("false".equals(isAdd) && item != null) {
                int i = 0;
                for (TaskEntity te : list) {
                    if (item.getTaskKey().equals(te.getTaskKey())) {
                        if (te.isOpenStart()) {
                            rmsg.setFlag("F");
                            rmsg.setMsg("任务已开启不能修改");
                            return rmsg;
                        }
                        list.remove(te);
                        break;
                    }
                    i++;
                }
                list.add(i, item);
                mark = XmlReader.newInstance().writeXml(list);
            } else {
                id = XmlReader.newInstance().noZero(list.size() + "", 3, "1");
                item.setTaskKey(id);
                list.add(item);
                mark = XmlReader.newInstance().writeXml(list);
                if (item.getTaskStatus() == 1) {
                    ScheduledExecutor.newInstance().start(id);
                }
            }
        }else{
            if ("false".equals(isAdd) && item != null) {
                ParamsVo vo = new ParamsVo();
                vo.setInfoId(item.getTaskKey());
                TaskEntity task = (TaskEntity)taskTimerManager.getInfoById(vo);
                if (task.isOpenStart()) {
                    rmsg.setFlag("F");
                    rmsg.setMsg("任务已开启不能修改");
                    return rmsg;
                }
                vo.setObj(item);
                mark = taskTimerManager.editInfo(vo);
            }else{
                ParamsVo vo = new ParamsVo();
                vo.setObj(item);
                id = taskTimerManager.saveInfo(vo);
            }
        }
        if (("false".equals(isAdd) && !mark) || ("true".equals(isAdd) && StrUtil.isNull(id))) {
            rmsg.setFlag("F");
            rmsg.setMsg("操作失败！");
        }
        return rmsg;
    }

    @RequestMapping("/task/list!data.action")
    @ResponseBody
    public Object data(HttpServletRequest request, String page, String rows) {
        Map<String, Object> mapData = new HashMap<String, Object>();
        String isFile = StrUtil.doNull(RpcUtil.getInstance().getValueByKey("read.file.database"),"file");
        if("file".equalsIgnoreCase(isFile)){
            List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
            mapData.put("total", list.size());
            mapData.put("rows", list);
        }else{
            ParamsVo vo = new ParamsVo();
            vo.setParams("pageIndex", page);
            vo.setParams("pageSize", rows);
            vo.setMethodKey("ForIds");
            Page pageList = taskTimerManager.getPageInfo(vo);
            if(!Validator.isEmpty(pageList.getPageObjects())) {
                List list = ScheduledExecutor.newInstance().getCache().getObjects(pageList.getPageObjects());
                pageList.setPageObjects(list);
            }
            mapData.put("total", pageList.getCount());
            mapData.put("rows", pageList.getPageObjects());
        }
        return mapData;
    }

    //开启线程
    @RequestMapping("/task/start.action")
    @ResponseBody
    public ResultMsg startTask(HttpServletRequest request, String key) {
        String ip = OsUtils.getLocalIp();
        String isFile = StrUtil.doNull(RpcUtil.getInstance().getValueByKey("read.file.database"),"file");
        if (StrUtil.isNull(key)) {//开启所有线程
            if("file".equalsIgnoreCase(isFile)) {
                ScheduledExecutor.newInstance().start();
            }else{
                return new ResultMsg("F", "暂不支持此项操作！");
                //ScheduledExecutor.newInstance().startBySysName("",ip);
            }
        } else {//开户指定线程
            if("file".equalsIgnoreCase(isFile)) {
                ScheduledExecutor.newInstance().start(key);
            }else{
                Object obj = ScheduledExecutor.newInstance().getCache().getCacheObjectByKey(key);
                if(null != obj){
                    TaskEntity task = (TaskEntity)obj;
                    if(!task.getServerIp().equals(ip)){
                        return new ResultMsg("F", "不能操作此任务！");
                    }else{
                        ScheduledExecutor.newInstance().start(task.getSysName(),key,ip);
                    }
                }
            }
        }
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        return rmsg;
    }

    @RequestMapping("/task/del.action")
    @ResponseBody
    public ResultMsg delTask(HttpServletRequest request, String key) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        if (StrUtil.isNotNull(key)) {//开启所有线程
            String isFile = StrUtil.doNull(RpcUtil.getInstance().getValueByKey("read.file.database"),"file");
            if("file".equalsIgnoreCase(isFile)){
                List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
                for (TaskEntity te : list) {
                    if (key.equals(te.getTaskKey())) {
                        if (te.isOpenStart()) {
                            rmsg.setFlag("F");
                            rmsg.setMsg("任务已开启不能删除");
                            return rmsg;
                        }
                        list.remove(te);
                        break;
                    }
                }
                XmlReader.newInstance().writeXml(list);
            }else{
                Object obj = ScheduledExecutor.newInstance().getCache().getCacheObjectByKey(key);
                if(null != obj){
                    TaskEntity task = (TaskEntity)obj;
                    if (task.isOpenStart()) {
                        rmsg.setFlag("F");
                        rmsg.setMsg("任务已开启不能删除");
                        return rmsg;
                    }
                }
                ParamsVo vo = new ParamsVo();
                vo.setInfoId(key);
                taskTimerManager.deleteInfo(vo);
            }
        }
        return rmsg;
    }

    //停止线程
    @RequestMapping("/task/stop.action")
    @ResponseBody
    public ResultMsg stop(HttpServletRequest request, String key) {
        String ip = OsUtils.getLocalIp();
        String isFile = StrUtil.doNull(RpcUtil.getInstance().getValueByKey("read.file.database"),"file");
        if (StrUtil.isNull(key)) {//开启所有线程
            if("file".equalsIgnoreCase(isFile)) {
                ScheduledExecutor.newInstance().stopTasks();
            }else{
                return new ResultMsg("F", "暂不支持此项操作！");
                //ScheduledExecutor.newInstance().stopTasks("",ip);
            }
        } else {//开户指定线程
            if("file".equalsIgnoreCase(isFile)) {
                ScheduledExecutor.newInstance().start(key);
            }else{
                Object obj = ScheduledExecutor.newInstance().getCache().getCacheObjectByKey(key);
                if(null !=obj){
                    TaskEntity task = (TaskEntity)obj;
                    if(!task.getServerIp().equals(ip)){
                        return new ResultMsg("F", "不能操作此任务！");
                    }else{
                        ScheduledExecutor.newInstance().stopTaskByKey(task.getSysName(),key,ip);
                    }
                }
            }
        }
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        return rmsg;
    }
    ///////////////以下完成系统数据源定义////////////////////////

    /**
     * 跳到列表页
     */
    @RequestMapping(value = "/source/list", method = RequestMethod.GET)
    public String toSourceList(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        return "/datasource/source-list";
    }

    /**
     * 跳到新增页
     */
    @RequestMapping(value = "/source/save", method = RequestMethod.GET)
    public String toSourceSave(HttpServletRequest request, Map<String, Object> data) {
        data.put("ctx", request.getContextPath());
        String id = request.getParameter("id");
        if (StrUtil.isNull(id)) {//新增
            data.put("item", new RpcDatasource());
            data.put("isAdd", "true");
        } else {
            ParamsVo<RpcDatasource> vo = new ParamsVo();
            vo.setInfoId(id);
            data.put("isAdd", "false");
            data.put("item", rpcDatasourceManager.getInfoById(vo));
        }
        return "/datasource/source-save";
    }

    @RequestMapping("/source/list!data.action")
    @ResponseBody
    public Object dataSource(HttpServletRequest request, String page, String rows) {

        ParamsVo<RpcDatasource> vo = new ParamsVo<RpcDatasource>();
        RpcDatasource register = new RpcDatasource();
        if (Validator.isNotNull(request.getParameter("sysEname"))) {
            register.setSysEname(request.getParameter("sysEname"));
        }
        if (Validator.isNotNull(request.getParameter("databaseType"))) {
            register.setDatabaseType(request.getParameter("databaseType"));
        }
        vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
        vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
        vo.setObj(register);
        Page pageList = rpcDatasourceManager.getPageInfo(vo);
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", pageList.getCount());
        mapData.put("rows", pageList.getPageObjects());
        return mapData;
    }

    @RequestMapping(value = "/source/save.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveSource(HttpServletRequest request, HttpServletResponse response,
            RpcDatasource item) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        String isAdd = request.getParameter("isAdd");
        if (Validator.isNull(item.getSysEname())) {
            rmsg = new ResultMsg("F", "数据源名称不能为空！");
            return rmsg;
        }
        ParamsVo<RpcDatasource> vo = new ParamsVo<RpcDatasource>();
        vo.setObj(item);
        String id = "";
        boolean mark = false;
        if ("false".equals(isAdd) && item != null) {
            mark = rpcDatasourceManager.editInfo(vo);
        } else {
            vo.setInfoId(item.getSysEname());
            Object obj = rpcDatasourceManager.getInfoById(vo);
            if (null != obj) {
                rmsg.setFlag("F");
                rmsg.setMsg("已存在" + item.getSysEname() + "系统数据源");
                return rmsg;
            }
            id = rpcDatasourceManager.saveInfo(vo);
        }
        if (("false".equals(isAdd) && !mark) || ("true".equals(isAdd) && StrUtil.isNull(id))) {
            rmsg.setFlag("F");
            rmsg.setMsg("操作失败！");
        }
        return rmsg;
    }

    @RequestMapping(value = "/source/del.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteSource(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<RpcDatasource> vo = new ParamsVo();
        if (StrUtil.isNotNull(id)) {
            vo.setInfoId(id);
            boolean mark = rpcDatasourceManager.deleteInfo(vo);
            if (!mark) {
                rmsg.setFlag("F");
                rmsg.setMsg("删除失败！");
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请不要恶意操作！");
        }

        return rmsg;
    }
}
